package com.qianxun.framework.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加解密工具
 * @author: huwei
 * @date:   2019/12/27 13:15
 * @version:  1.0.0
*/
public class AESUtil {
//
//    public static void main(String[] args) {
//        String secretKey = UUID.randomUUID().toString().replace("-","");
//        System.err.println(secretKey);
//        byte[] encryptBytes = AESUtil.getInstance().encrypt("123".getBytes() ,secretKey.getBytes());
//
//        byte[] decryptBytes = AESUtil.getInstance().decrypt(encryptBytes ,secretKey.getBytes());
//        System.err.println(new String(decryptBytes));
//    }

    /**
     * 单例
     */
    private AESUtil(){}

    public static AESUtil getInstance(){
        return AESHolder.instance;
    }

    private final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    private final String ALGORITHM = "AES";
    /**
     * 异常
     */
    private final ThreadLocal<Exception> cause = new InheritableThreadLocal<>();

    /**
     * 加密
     * @param content 原数据
     * @param secret 密钥 ,固定长度16或32个字符
     * @return 加密成功返回加密数据，反之 null
     */
    public byte[] encrypt(byte[] content, byte[] secret) {
        if (content == null || secret == null) {
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret, ALGORITHM));
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
            cause.set(e);
        }
        return null;
    }

    /**
     * 解密
     * @param content 加密数据
     * @param secret 密钥 ,固定长度16或32个字符
     * @return 解密成功返回原数据，反之 null
     */
    public byte[] decrypt(byte[] content, byte[] secret) {
        if (content == null || secret == null) {
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret, ALGORITHM));
            byte[] bytes = cipher.doFinal(content);
            return bytes;
        }catch (Exception e){
            e.printStackTrace();
            cause.set(e);
        }
        return null;
    }

    /**
     * 获取加解密时的错误信息
     * @return
     */
    public Exception getAndRemoveErrorCause(){
        Exception exception = cause.get();
        cause.remove();
        return exception;
    }

    /**
     * 静态初始
     */
    private static final class AESHolder {
        static final AESUtil instance = new AESUtil();
    }
}

